from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.conf import settings
from django.core.mail import EmailMessage

import logging

from c_ntact.forms import ContactForm

def form(request, template_name="c_ntact/form.html"):
    """
    The contact form
    """
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            reply_to = "%s <%s>" % (form.cleaned_data.get('name'), form.cleaned_data.get('email'))
            body = """
            %s contact form:
            
            from: %s
            phone: %s
            url: %s
            
            %s
            """ % (settings.APP_NAME, reply_to, form.cleaned_data.get('phone'), form.cleaned_data.get('url'), form.cleaned_data.get('message'))
            subject = form.cleaned_data.get('subject')
            try:
                message = EmailMessage(subject=subject, body=body, to=[settings.ADMIN_EMAIL],
                                       headers = {'Reply-To': reply_to})
                message.send()
            except Exception, e:
                logging.error("""error sending message: %s
                subject: %s
                %s
                """ % (e, subject, body))
                raise
            return HttpResponseRedirect(reverse('c_ntact_thanks'))
    else:
        form = ContactForm()
    return render_to_response(template_name, {'form':form, 'nav_page':'c_ntact_form'},
                              context_instance=RequestContext(request))

def thanks(request, template_name="c_ntact/thanks.html"):
    """
    A simple thank you page
    """
    return render_to_response(template_name, {},
                          context_instance=RequestContext(request))